﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using Microsoft.SharePoint.Administration;
using System.IO;
using System.Threading;
using System.ComponentModel;
using Microsoft.SharePoint;
using System.Windows.Media.Animation;

namespace ApplicationsCenter
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Members
        Grid _solutionsGrid;
        List<Grid> _items;
        bool _checked;
        SPFarm _farm;
        bool? _featureFlag;
        string _fileName;
        string _url;
        string _filePath;
        string _featurePath;
        Thread _uIThread;
        bool _globalFlag;
        Storyboard storyboard;
        #endregion

        #region Initializing Components & Members
        public MainWindow()
        {
            InitializeComponent();
            _checked = false;
            _items = new List<Grid>();
            _farm = new SPFarm();
            _featureFlag = false;
            _fileName = string.Empty;
            _url = string.Empty;
            _filePath = string.Empty;
            _featurePath = string.Empty;
            _uIThread = Thread.CurrentThread;
            _globalFlag = false;
            featureBrowseTextBox.Visibility = Visibility.Hidden;
            featureBrowserButton.Visibility = Visibility.Hidden;
            featureTextBlock.Visibility = Visibility.Hidden;
            storyboard = new Storyboard();
        }
        #endregion

        #region Importing Solutions

        #region Selecting and Deselecting all items
        private void CheckItem(bool flag)
        {
            foreach (Grid g in solutionsListBox.Items)
            {
                foreach (Object obj in g.Children)
                {
                    if (obj is System.Windows.Controls.CheckBox)
                    {
                        ((System.Windows.Controls.CheckBox)obj).IsChecked = flag;
                    }
                }
            }
        }
        #endregion

        #region Get Items
        /// <summary>
        /// Get solutions that exist within the farm
        /// </summary>
        /// <returns>Farm solutions</returns>
        private List<string> GetItems()
        {
            List<string> checkedItems = new List<string>();
            foreach (Grid g in solutionsListBox.Items)
            {
                int flag = 0;
                bool checkedFlag = false;
                string state = string.Empty;
                foreach (Object obj in g.Children)
                {
                    if (obj is System.Windows.Controls.CheckBox)
                    {
                        flag = 1;
                        checkedFlag = (bool)((System.Windows.Controls.CheckBox)obj).IsChecked;
                    }
                    if (flag == 1)
                    {
                        if (obj is TextBlock)
                        {
                            if (((TextBlock)obj).Text.Length > 0)
                            {
                                state = ((TextBlock)obj).Text;
                                if (checkedFlag)
                                {
                                    //Check if the solution is deployed or not
                                    if (state.ToLower() != "deployed" && state.ToLower() != "not deployed")
                                        checkedItems.Add(state);
                                }
                            }
                            flag = 0;
                        }
                    }
                }
            }
            return checkedItems;
        }

        #endregion

        #region Events

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            aboutTextBlock.Text = "In order for the application to work properly please make sure that : " + Environment.NewLine + "1- You're an administrator." + Environment.NewLine + "2- You're an administrator of the farm where you're deploying the solution." + Environment.NewLine + "3- You're a database administrator where the farm database exists." + Environment.NewLine + "4- The url you're using exists." + Environment.NewLine + "5- If you're deploying a solution as a feature make sure that your feature has the attribute AlwaysForceInstall='TRUE'." + Environment.NewLine + "	Ex: <Feature AlwaysForceInstall='TRUE'>" + Environment.NewLine + Environment.NewLine + "Go to local services and make sure these services are started: " + Environment.NewLine + "1- SharePoint 2010 Administration " + Environment.NewLine + "2- SharePoint 2010 Timer " + Environment.NewLine + "3- SQL Server " + Environment.NewLine + "4- SQL Server Agent "+ Environment.NewLine + Environment.NewLine + Environment.NewLine +"*Tested on Sharepoint 2010*";
            _farm = SPFarm.Local; //Get the local farm
            
            //Adding Farm Web Applications Urls To The ComboBox
            foreach (SPAlternateUrlCollection url in _farm.AlternateUrlCollections)
            {
                foreach (SPAlternateUrl u in url)
                {
                    urlsComboBox.Items.Add(u.Uri.AbsoluteUri);
                }
            }
            urlsComboBox.Items.Add("Deploy Globally");
            try
            {
                if (_farm != null)
                {
                    SPSolutionCollection solutions = _farm.Solutions;
                    if (solutions.Count > 0)
                    {
                        //Creating a check box and a state field for each solution
                        foreach (SPSolution solution in solutions)
                        {
                            SPPersistedFile wspFile = solution.SolutionFile;
                            System.Windows.Controls.CheckBox checkBox = new System.Windows.Controls.CheckBox();
                            _solutionsGrid = new Grid();
                            TextBlock solutionName = new TextBlock();
                            TextBlock deploymentStates = new TextBlock();

                            ColumnDefinition firstCol = new ColumnDefinition();
                            firstCol.Width = new GridLength(23);
                            _solutionsGrid.ColumnDefinitions.Add(firstCol);

                            ColumnDefinition secCol = new ColumnDefinition();
                            secCol.Width = new GridLength(375);
                            _solutionsGrid.ColumnDefinitions.Add(secCol);

                            ColumnDefinition thirdCol = new ColumnDefinition();
                            thirdCol.Width = new GridLength(94);
                            _solutionsGrid.ColumnDefinitions.Add(thirdCol);

                            RowDefinition itemRow = new RowDefinition();
                            itemRow.Height = GridLength.Auto;
                            _solutionsGrid.RowDefinitions.Add(itemRow);

                            checkBox.IsChecked = _checked;
                            checkBox.IsEnabled = true;
                            checkBox.HorizontalAlignment = HorizontalAlignment;
                            solutionName.Text = solution.DisplayName;
                            checkBox.Margin = new Thickness(0, 2, 10, 0);
                            deploymentStates.Margin = new Thickness(0, 0, 0, 0);
                            solutionName.Margin = new Thickness(0, 0, 0, 0);

                            _solutionsGrid.Children.Add(checkBox);
                            Grid.SetColumn(checkBox, 0);
                            Grid.SetRow(checkBox, 0);

                            string str = string.Empty;
                            if (solution.Deployed)
                            {
                                str = "Deployed";
                            }
                            else
                            {
                                str = "Not Deployed";
                            }

                            deploymentStates.Text = str;
                            solutionName.Text = solution.Name;
                            _solutionsGrid.Children.Add(solutionName);
                            Grid.SetColumn(solutionName, 1);
                            Grid.SetRow(solutionName, 0);

                            _solutionsGrid.Children.Add(deploymentStates);
                            Grid.SetColumn(deploymentStates, 2);
                            Grid.SetRow(deploymentStates, 0);

                            _items.Add(_solutionsGrid);
                            solutionsListBox.ItemsSource = _items;
                            solutionsListBox.Items.Refresh();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        //Downloading solutions and saving them to a specific folder chosen by the user
        private void exportButton_Click(object sender, RoutedEventArgs e)
        {
            
            if (_farm != null)
            {
                List<string> checkedItems = new List<string>();
                checkedItems = GetItems();
                if (checkedItems.Count > 0)
                {
                    FolderBrowserDialog solutionsFolderBrowserDialog = new FolderBrowserDialog();
                    solutionsFolderBrowserDialog.ShowDialog();
                    if (solutionsFolderBrowserDialog.SelectedPath != null && solutionsFolderBrowserDialog.SelectedPath.Length > 0)
                    {
                        foreach (string s in GetItems())
                        {
                            SPPersistedFile wspFile = _farm.Solutions[s].SolutionFile;
                            DirectoryInfo dir = new DirectoryInfo(solutionsFolderBrowserDialog.SelectedPath);
                            if (!dir.Exists)
                            {
                                dir.Create();
                            }
                            wspFile.SaveAs(solutionsFolderBrowserDialog.SelectedPath + "\\" + _farm.Solutions[s].Name);
                        }
                        System.Windows.Forms.MessageBox.Show("Solutions exported successfully to " + solutionsFolderBrowserDialog.SelectedPath, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Please choose a valid path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("No solutions to export", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("We couldn't find any farm. Please verify that you're logged as a local administrator, a farm administrator and that you're farm database administrator", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void selectAllButton_Click(object sender, RoutedEventArgs e)
        {
            CheckItem(true);
        }

        private void deSelectAllButton_Click(object sender, RoutedEventArgs e)
        {
            CheckItem(false);
        }

        #endregion

        #endregion

        #region deployment

        #region Worker Events

        void _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + e.UserState.ToString(); });
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            // run all background tasks here
            if (_url.ToLower().Contains("deploy globally"))
            {
                _globalFlag = true;
            }
            DeployManager(_fileName, _url, _filePath, _featurePath);
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            featureBrowseTextBox.IsEnabled = true;
            featureBrowserButton.IsEnabled = true;
            urlsComboBox.IsEnabled = true;
            fileBrowserButton.IsEnabled = true;
            fileBrowseTextBox.IsEnabled = true;
            featureCheckBox.IsEnabled = true;
            deployButton.IsEnabled = true;
        }

        #endregion

        #region Deploy Manager
        public void DeployManager(string fileName, string webApplication, string filePath, string featurePath)
        {
            if (_globalFlag)
            {
                #region Deploying Globally
                try
                {
                    bool isDeployed = false;
                    FileInfo _featureFile;
                    if (!RetractSolution(fileName))
                    {
                        RemoveSolution(fileName);
                        Thread.Sleep(3000);

                        _farm.Solutions.Add(filePath);
                        Thread.Sleep(3000);
                        Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + "Deploying solution"; });

                        bool deployedflag=false;
                        //Wait for other jobs to end before starting the deployment
                        while (!deployedflag)
                        {
                            Thread.Sleep(1000);
                            if (!_farm.Solutions[fileName].JobExists)
                            {
                                _farm.Solutions[fileName].Deploy(DateTime.Now, true, true);
                                deployedflag = true;
                            }
                        }
                        //wait for the solution to be deployed
                        while (!isDeployed)
                        {
                            Thread.Sleep(1000);
                            if (!_farm.Solutions[fileName].JobExists)
                            {
                                isDeployed = _farm.Solutions[fileName].Deployed;
                            }
                        }

                        Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + "Solution is deployed"; });
                        
                        if (_featureFlag == true)
                        {
                            if (featurePath.Length > 0)
                            {
                                try
                                {
                                    _featureFile = new FileInfo(featurePath);
                                    DirectoryInfo dir = new DirectoryInfo(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\" + _featureFile.Directory.Name);
                                    if (dir.Exists)
                                    {
                                        dir.Delete(true);
                                    }
                                    //Copy the feature file to the sharepoint default features' Path
                                    DirectorCopyClass.DirectoryCopy(_featureFile.DirectoryName, @"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\" + _featureFile.Directory.Name, true);
                                    //Adding Feature to farm and activating it
                                    _farm.FeatureDefinitions.Add(_featureFile.Directory.Name + @"\" + _featureFile.Name, _farm.Solutions[fileName].SolutionId, true);
                                }
                                catch (Exception ex)
                                {
                                    System.Windows.Forms.MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                #endregion
            }
            else
            {
                #region Deploying to a specific web application
                try
                {
                    FileInfo _featureFile;
                    SPSite site;
                    SPWeb Web;
                    SPWebApplication spWeb;
                    bool isDeployed = false;
                    string webUrl = string.Empty;
                    System.Collections.ObjectModel.Collection<SPWebApplication> webs = new System.Collections.ObjectModel.Collection<SPWebApplication>();
                    site = new SPSite(webApplication);
                    Web = site.OpenWeb();
                    spWeb = Web.Site.WebApplication;

                    webs.Add(spWeb);

                    if (!RetractSolution(fileName, spWeb))
                    {
                        RemoveSolution(fileName);
                        Thread.Sleep(3000);

                        _farm.Solutions.Add(filePath);
                        Thread.Sleep(3000);

                        Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + "Deploying solution"; });
                        bool deployedFlag = false;
                        //Wait for other jobs to end before starting the deployment
                        while (!deployedFlag)
                        {
                            if (!_farm.Solutions[fileName].JobExists)
                            {
                                _farm.Solutions[fileName].Deploy(DateTime.Now, true, webs, true);
                                deployedFlag = true;
                            }
                        }
                        //wait for the solution to be deployed
                        while (!isDeployed)
                        {
                            Thread.Sleep(1000);
                            if (!_farm.Solutions[fileName].JobExists)
                            {
                                isDeployed = _farm.Solutions[fileName].DeployedWebApplications.Contains(spWeb);
                            }
                        }
                        Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + "Solution is deployed"; });
                        if (_featureFlag == true)
                        {
                            if (featurePath.Length > 0)
                            {
                                try
                                {
                                    _featureFile = new FileInfo(featurePath);
                                    DirectoryInfo dir = new DirectoryInfo(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\" + _featureFile.Directory.Name);
                                    if (dir.Exists)
                                    {
                                        dir.Delete(true);
                                    }
                                    //Copy the feature file to the sharepoint default features' Path
                                    DirectorCopyClass.DirectoryCopy(_featureFile.DirectoryName, @"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\" + _featureFile.Directory.Name, true);
                                    //Adding Feature to farm and activating it
                                    site.FeatureDefinitions.Add(_featureFile.Directory.Name + @"\" + _featureFile.Name, _farm.Solutions[fileName].SolutionId, true);
                                }
                                catch (Exception ex)
                                {
                                    System.Windows.Forms.MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                #endregion
            }
        }
        #endregion

        #region Solution Operators

        /// <summary>
        /// Retract Solution From A Specified WebApplication
        /// </summary>
        /// <param name="fileName">solution name</param>
        /// <param name="spWeb">web application</param>
        /// <returns>Bool</returns>
        bool RetractSolution(string fileName, SPWebApplication spWeb)
        {
            bool isDeployed = false;
            System.Collections.ObjectModel.Collection<SPWebApplication> webs = new System.Collections.ObjectModel.Collection<SPWebApplication>();
            webs.Add(spWeb);
            if (SolutionExists(fileName))
            {
                try
                {
                    isDeployed = _farm.Solutions[fileName].DeployedWebApplications.Contains(spWeb); //Check if the solution is deployed on web applications
                    if (!_farm.Solutions[fileName].JobExists)
                    {
                        if (isDeployed)
                        {
                            _farm.Solutions[fileName].Retract(DateTime.Now, webs); //Retracts the solution from a specific Web application
                            Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + "Retracting existing solution"; });
                        }
                        //Loop to wait for the solution to be retracted
                        while (isDeployed)
                        {
                            Thread.Sleep(1000);
                            isDeployed = _farm.Solutions[fileName].DeployedWebApplications.Contains(spWeb);//Check if the solution is deployed on web applications
                        }
                        if (isDeployed)
                        {
                            isDeployed = false;
                        }
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Solution deployment is aborted because there's another job currently running", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + "Aborted..."; });
                    }
                }
                catch (InvalidOperationException ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return isDeployed;
        }

        /// <summary>
        /// Retract Solution Globally
        /// </summary>
        /// <param name="fileName">solution name</param>
        /// <returns>Bool</returns>
        bool RetractSolution(string fileName)
        {
            bool isDeployed = false;
            if (SolutionExists(fileName))
            {
                try
                {
                    isDeployed = _farm.Solutions[fileName].Deployed; //Check if the solution is deployed
                    if (!_farm.Solutions[fileName].JobExists)
                    {
                        if (isDeployed)
                        {
                            _farm.Solutions[fileName].Retract(DateTime.Now);//Retract the solution Globally
                            Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + "Retracting existing solution"; });
                        }
                        while (isDeployed)
                        {
                            Thread.Sleep(1000);
                            isDeployed = _farm.Solutions[fileName].Deployed;//Check if the solution is deployed
                        }
                        if (isDeployed)
                        {
                            isDeployed = false;
                        }
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Solution deployment is aborted because there's another job currently running", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + "Aborted..."; });
                    }
                }
                catch (InvalidOperationException ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return isDeployed;
        }

        /// <summary>
        /// Remove Solution From Local Farm
        /// </summary>
        /// <param name="fileName">solution name</param>
        void RemoveSolution(string fileName)
        {
            if (SolutionExists(fileName))
            {
                Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + "Removing solution"; });
                _farm.Solutions[fileName].Delete();
                while (true)
                {
                    try
                    {
                        string str = _farm.Solutions[fileName].Name;
                    }
                    catch (Exception)
                    {
                        Dispatcher.Invoke((Action)delegate { resultTextBox.Text += Environment.NewLine + "Solution is removed"; });
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Check if solution exists in the local farm
        /// </summary>
        /// <param name="fileName">Solution Name</param>
        /// <returns>Bool</returns>
        bool SolutionExists(string fileName)
        {
            try
            {
                string str = _farm.Solutions[fileName].Name;
                if (str == fileName.ToLower())
                {
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return false;
        }

        #endregion

        #region Events

        private void fileBrowserButton_Click(object sender, RoutedEventArgs e)
        {
            //Browse for the sharepoint solution file
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "Sharepoint Project(.wsp)|*.wsp|All Files (*.*)|*.*";
            fileDialog.FilterIndex = 1;
            fileDialog.ShowDialog();
            fileBrowseTextBox.Text = fileDialog.FileName;
        }

        private void featureBrowserButton_Click(object sender, RoutedEventArgs e)
        {
            //Browse for the feature file
            OpenFileDialog featureFileDialog = new OpenFileDialog();
            featureFileDialog.Filter = "Feature(.xml)|*.xml|All Files (*.*)|*.*";
            featureFileDialog.FilterIndex = 1;
            featureFileDialog.ShowDialog();
            featureBrowseTextBox.Text = featureFileDialog.FileName;
        }

        private void deployButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (urlsComboBox.SelectedValue != null)
                {
                    if (fileBrowseTextBox.Text.Trim().Length > 0)
                    {
                        if (fileBrowseTextBox.Text.Contains('\\'))
                        {
                            BackgroundWorker _worker = new BackgroundWorker(); //Creating a new worker to run sharepoint operations on
                            string[] fileName = fileBrowseTextBox.Text.Split('\\');
                            _fileName = fileName[fileName.Length - 1];
                            _url = urlsComboBox.SelectedValue.ToString();
                            _filePath = fileBrowseTextBox.Text;
                            _featurePath = featureBrowseTextBox.Text;
                            if (featureCheckBox.IsChecked == true)
                            {
                                if (featureBrowseTextBox.Text.Trim().Length > 0)
                                {
                                    if (_globalFlag)
                                    {
                                        resultTextBox.Text = "Attempting to deploy " + _fileName + " Globally " + Environment.NewLine;
                                    }
                                    else
                                    {
                                        resultTextBox.Text = "Attempting to deploy " + _fileName + " to web application " + urlsComboBox.SelectedValue.ToString() + Environment.NewLine;
                                    }
                                    _worker.DoWork += worker_DoWork;
                                    _worker.RunWorkerCompleted += worker_RunWorkerCompleted;
                                    _worker.WorkerReportsProgress = true;
                                    _worker.ProgressChanged += new ProgressChangedEventHandler(_worker_ProgressChanged);
                                    _worker.RunWorkerAsync();
                                    featureBrowseTextBox.IsEnabled = false;
                                    featureBrowserButton.IsEnabled = false;
                                    urlsComboBox.IsEnabled = false;
                                    fileBrowserButton.IsEnabled = false;
                                    fileBrowseTextBox.IsEnabled = false;
                                    featureCheckBox.IsEnabled = false;
                                    deployButton.IsEnabled = false;
                                }
                                else
                                {
                                    System.Windows.MessageBox.Show("Please enter a valid feature path");
                                }
                            }
                            else
                            {
                                if (_globalFlag)
                                {
                                    resultTextBox.Text = "Attempting to deploy " + _fileName + " Globally " + Environment.NewLine;
                                }
                                else
                                {
                                    resultTextBox.Text = "Attempting to deploy " + _fileName + " to web application " + urlsComboBox.SelectedValue.ToString() + Environment.NewLine;
                                }
                                _worker.DoWork += worker_DoWork;
                                _worker.RunWorkerCompleted += worker_RunWorkerCompleted;
                                _worker.WorkerReportsProgress = true;
                                _worker.ProgressChanged += new ProgressChangedEventHandler(_worker_ProgressChanged);
                                _worker.RunWorkerAsync();
                                featureBrowseTextBox.IsEnabled = false;
                                featureBrowserButton.IsEnabled = false;
                                urlsComboBox.IsEnabled = false;
                                fileBrowserButton.IsEnabled = false;
                                fileBrowseTextBox.IsEnabled = false;
                                featureCheckBox.IsEnabled = false;
                                deployButton.IsEnabled = false;
                            }
                        }
                        else
                        {

                        }
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("Please enter a valid file path");
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show("Please choose your web application");
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void featureCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            _featureFlag = featureCheckBox.IsChecked;
            featureBrowseTextBox.Visibility = Visibility.Visible;
            featureBrowserButton.Visibility = Visibility.Visible;
            featureTextBlock.Visibility = Visibility.Visible;
        }

        private void featureCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            _featureFlag = featureCheckBox.IsChecked;
            featureBrowseTextBox.Visibility = Visibility.Hidden;
            featureBrowserButton.Visibility = Visibility.Hidden;
            featureTextBlock.Visibility = Visibility.Hidden;
        }

        private void urlsComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (urlsComboBox.SelectedValue.ToString().ToLower().Contains("deploy globally"))
            {
                _globalFlag = true;
            }
            else
            {
                _globalFlag = false;
            }
        }

        #endregion

        #endregion

        #region Animation

        private void deploymentSectionButton_Click(object sender, RoutedEventArgs e)
        {
            aboutTextBlock.Visibility = Visibility.Hidden;
            #region Fade in
            // Create a storyboard to contain the animations.
            storyboard.Stop(this);
            TimeSpan duration = new TimeSpan(0, 0, 2);

            // Create a DoubleAnimation to fade the not selected option control
            DoubleAnimation animation = new DoubleAnimation();
            animation.From = 0.0;
            animation.To = 1.0;
            animation.Duration = new Duration(duration);
            deploymentToolGrid.Visibility = Visibility.Visible;
            importingToolGrid.Visibility = Visibility.Hidden;
            deploymentOuterBorder.Visibility = Visibility.Visible;
            importingOuterBorder.Visibility = Visibility.Hidden;
            titleTextBlock.Text = "Deployment Tool";
            titleShadowTextBlock.Text = "Deployment Tool";
            // Configure the animation to target the property Opacity
            Storyboard.SetTargetName(animation, deploymentOuterBorder.Name);
            Storyboard.SetTargetProperty(animation, new PropertyPath(System.Windows.Controls.Control.OpacityProperty));
            // Add the animation to the storyboard
            storyboard.Children.Add(animation);
            animation.AutoReverse = false;

            // Begin the storyboard
            storyboard.AutoReverse=false;
            storyboard.Begin(this);
            #endregion
        }

        private void importingSectionButton_Click(object sender, RoutedEventArgs e)
        {
            aboutTextBlock.Visibility = Visibility.Hidden;
            #region Fade in
            // Create a storyboard to contain the animations.
            storyboard.Stop(this);
            TimeSpan duration = new TimeSpan(0, 0, 2);

            // Create a DoubleAnimation to fade the not selected option control
            DoubleAnimation animation = new DoubleAnimation();
            animation.From = 0.0;
            animation.To = 1.0;
            animation.Duration = new Duration(duration);
            deploymentToolGrid.Visibility = Visibility.Hidden;
            importingToolGrid.Visibility = Visibility.Visible;
            deploymentOuterBorder.Visibility = Visibility.Hidden;
            importingOuterBorder.Visibility = Visibility.Visible;
            titleTextBlock.Text = "Importing Solution Tool";
            titleShadowTextBlock.Text = "Importing Solution Tool";
            // Configure the animation to target the property Opacity
            Storyboard.SetTargetName(animation, importingOuterBorder.Name);
            Storyboard.SetTargetProperty(animation, new PropertyPath(System.Windows.Controls.Control.OpacityProperty));
            // Add the animation to the storyboard
            storyboard.Children.Add(animation);
            storyboard.AutoReverse = false;

            // Begin the storyboard
            storyboard.Begin(this);

            #endregion
        }

        #endregion

        #region Main Window Events
        private void deploymentSectionButton_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            //Change the mouse pointer to Hand when entering th deploymentSectionButton
            e.MouseDevice.OverrideCursor = System.Windows.Input.Cursors.Hand;
        }

        private void deploymentSectionButton_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            //Change the mouse pointer to Arrow after leaving th deploymentSectionButton
            e.MouseDevice.OverrideCursor = System.Windows.Input.Cursors.Arrow;
        }

        private void closeButton_Click(object sender, RoutedEventArgs e)
        {
            //Closes the form
            this.Close();
        }

        private void aboutButton_Click(object sender, RoutedEventArgs e)
        {
            //Opens the about form
            About about = new About();
            about.ShowDialog();
        }
        #endregion
    }
}
